package com.bitcat.todoapp.demo.component

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.todoapp.R
import com.bitcat.todoapp.databinding.ActivitySpinnerBinding
import com.bitcat.todoapp.utils.ToastUtil

class SpinnerActivity : AppCompatActivity() {

    private val binding: ActivitySpinnerBinding by lazy {
        ActivitySpinnerBinding.inflate(layoutInflater)
    }

    private var  isFirst = true
    private var  isFirst2 = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        //监听下拉框
        binding.spinnerStatic.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {

                if (isFirst){
                    isFirst = false
                    return
                }

                val item =parent?.getItemAtPosition(position)
                ToastUtil.showToast("$item")
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

        }


        //动态加载
        val hobby = arrayOf("运动", "游戏", "音乐", "阅读", "旅行")
        val adapter = ArrayAdapter(this,android.R.layout.simple_spinner_item,hobby)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spinnerDynamic.adapter = adapter

        binding.spinnerDynamic.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {

                if (isFirst2){
                    isFirst2 = false
                    return
                }

                val item = hobby[position]
                ToastUtil.showToast("$item")
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

        }

    }
}